package dq.study.shiro.encrypt;

import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.*;
import org.apache.shiro.util.SimpleByteSource;

import java.util.HashSet;

/**
 *  散列算法
 * @author dongqun
 * @date 2020/4/13 13:50
 */
public class Hash {
    public static void main(String[] args) {
        String source = "hello";
        String salt = "123";
        //MD5
        String md5 = new Md5Hash(source, salt).toString();
        System.out.println(md5);
        //MD5 散列两次
        md5 = new Md5Hash(source, salt, 2).toString();
        System.out.println(md5);
        //SHA-1
        String sha1 = new Sha1Hash(source, salt).toString();
        System.out.println(sha1);
        //通用方式
        String simple = new SimpleHash("MD5", source, salt).toString();
        System.out.println(simple);
        //HasService + HashRequest
        DefaultHashService hashService = new DefaultHashService();
        hashService.setHashAlgorithmName("MD5");
        hashService.setPrivateSalt(new SimpleByteSource("123".getBytes()));//私盐
        hashService.setGeneratePublicSalt(true);
        hashService.setRandomNumberGenerator(new SecureRandomNumberGenerator());//公掩 生成一个随机数
        hashService.setHashIterations(2);

        HashRequest hashRequest = new HashRequest.Builder()
                .setAlgorithmName("MD5")
                .setSource("hello")
                .setSalt("123")
                .setIterations(2)
                .build();

        String hex = hashService.computeHash(hashRequest).toHex();
        System.out.println(hex);

        SecureRandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
        randomNumberGenerator.setSeed("123".getBytes());
        String hex2 = randomNumberGenerator.nextBytes().toHex();
        System.out.println(hex2);
    }
}
